<template>
  <div class="chat-page">
    <div class="sidebar">
      <div class="sidebar-header">
        <h2>AI Chat System</h2>
      </div>
      <div class="conversations">
        <div class="conversation-item" 
             v-for="conversation in conversations" 
             :key="conversation.id"
             :class="{ active: selectedConversationId === conversation.id }"
             @click="selectConversation(conversation.id)">
          <h3>{{ conversation.title }}</h3>
          <p class="last-message">{{ getLastMessage(conversation.id) }}</p>
        </div>
        <button class="new-conversation-btn" @click="createNewConversation">
          <i class="fa fa-plus"></i> 新建对话
        </button>
      </div>
    </div>
    <div class="chat-container">
      <div class="chat-header">
        <h2>{{ selectedConversationTitle }}</h2>
        <button class="delete-btn" @click="deleteConversation">
          <i class="fa fa-trash"></i> 删除对话
        </button>
      </div>
      <div class="message-list">
        <div class="message" 
             v-for="message in messages" 
             :key="message.id"
             :class="{ 'user-message': message.sender === 'user', 'agent-message': message.sender === 'agent' }">
          <div class="avatar">
            <img :src="getMessageAvatar(message.sender)" alt="Avatar">
          </div>
          <div class="content">
            <p>{{ message.content }}</p>
            <span class="time">{{ formatTime(message.createTime) }}</span>
          </div>
        </div>
      </div>
      <div class="input-area">
        <textarea v-model="messageContent" 
                  placeholder="输入消息..." 
                  @keydown.enter="sendMessage"></textarea>
        <button class="send-btn" @click="sendMessage">
          <i class="fa fa-paper-plane"></i> 发送
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'ChatPage',
  setup() {
    const conversations = ref([]);
    const messages = ref([]);
    const selectedConversationId = ref(null);
    const selectedConversationTitle = ref('选择一个对话开始聊天');
    const messageContent = ref('');
    const userId = ref(1); // 示例用户ID

    // 获取对话列表
    const fetchConversations = async () => {
      try {
        const response = await axios.get('/api/chat/conversations', {
          params: { userId: userId.value }
        });
        conversations.value = response.data.data;
      } catch (error) {
        console.error('获取对话列表失败:', error);
      }
    };

    // 选择对话
    const selectConversation = async (id) => {
      selectedConversationId.value = id;
      const conversation = conversations.value.find(c => c.id === id);
      if (conversation) {
        selectedConversationTitle.value = conversation.title;
        await fetchMessages(id);
      }
    };

    // 获取消息列表
    const fetchMessages = async (conversationId) => {
      try {
        const response = await axios.get('/api/chat/messages', {
          params: { conversationId }
        });
        messages.value = response.data.data;
      } catch (error) {
        console.error('获取消息列表失败:', error);
      }
    };

    // 发送消息
    const sendMessage = async () => {
      if (!messageContent.value.trim() || !selectedConversationId.value) return;

      try {
        // 发送用户消息
        await axios.post('/api/chat/messages', {
          conversationId: selectedConversationId.value,
          content: messageContent.value,
          sender: 'user'
        });

        // 模拟AI回复（实际项目中应调用AI接口）
        setTimeout(async () => {
          await axios.post('/api/chat/messages', {
            conversationId: selectedConversationId.value,
            content: '这是AI的回复示例，实际项目中会调用AI模型生成回复。',
            sender: 'agent'
          });
          await fetchMessages(selectedConversationId.value);
        }, 500);

        messageContent.value = '';
        await fetchMessages(selectedConversationId.value);
      } catch (error) {
        console.error('发送消息失败:', error);
      }
    };

    // 创建新对话
    const createNewConversation = async () => {
      const title = prompt('请输入对话标题:');
      if (!title) return;

      try {
        const response = await axios.post('/api/chat/conversations', {
          userId: userId.value,
          title
        });
        const newConversation = response.data.data;
        conversations.value.push(newConversation);
        selectedConversationId.value = newConversation.id;
        selectedConversationTitle.value = title;
        messages.value = [];
      } catch (error) {
        console.error('创建对话失败:', error);
      }
    };

    // 删除对话
    const deleteConversation = async () => {
      if (!selectedConversationId.value) return;
      if (!confirm('确定要删除此对话吗？')) return;

      try {
        await axios.delete(`/api/chat/conversations/${selectedConversationId.value}`);
        conversations.value = conversations.value.filter(c => c.id !== selectedConversationId.value);
        selectedConversationId.value = null;
        selectedConversationTitle.value = '选择一个对话开始聊天';
        messages.value = [];
      } catch (error) {
        console.error('删除对话失败:', error);
      }
    };

    // 获取最后一条消息内容
    const getLastMessage = (conversationId) => {
      const conversationMessages = messages.value.filter(m => m.conversationId === conversationId);
      if (conversationMessages.length > 0) {
        const lastMessage = conversationMessages[conversationMessages.length - 1];
        return lastMessage.content.length > 20 ? lastMessage.content.substring(0, 20) + '...' : lastMessage.content;
      }
      return '无消息';
    };

    // 获取消息头像
    const getMessageAvatar = (sender) => {
      return sender === 'user' ? '/static/user-avatar.png' : '/static/agent-avatar.png';
    };

    // 格式化时间
    const formatTime = (time) => {
      const date = new Date(time);
      return date.toLocaleTimeString();
    };

    onMounted(() => {
      fetchConversations();
    });

    return {
      conversations,
      messages,
      selectedConversationId,
      selectedConversationTitle,
      messageContent,
      fetchConversations,
      selectConversation,
      fetchMessages,
      sendMessage,
      createNewConversation,
      deleteConversation,
      getLastMessage,
      getMessageAvatar,
      formatTime
    };
  }
};
</script>

<style scoped>
.chat-page {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  background-color: #f5f5f5;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #ddd;
}

.conversations {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.conversation-item {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.conversation-item.active {
  background-color: #e0e0e0;
}

.conversation-item:hover {
  background-color: #e9e9e9;
}

.last-message {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.new-conversation-btn {
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 10px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delete-btn {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.content {
  max-width: 80%;
}

.user-message .content {
  background-color: #e0f7fa;
  padding: 10px;
  border-radius: 10px;
}

.agent-message .content {
  background-color: #f1f8e9;
  padding: 10px;
  border-radius: 10px;
}

.time {
  font-size: 10px;
  color: #666;
  display: block;
  margin-top: 5px;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #ddd;
  display: flex;
}

textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-right: 10px;
  resize: none;
}

.send-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}
</style>    